package com.imut.lagain.service.impl;

import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imut.lagain.entity.Notification;
import com.imut.lagain.entity.NotificationTemplate;
import com.imut.lagain.entity.WechatNotification;
import com.imut.lagain.mapper.WechatNotificationMapper;
import com.imut.lagain.repository.WechatNotificationRepository;
import com.imut.lagain.service.IWechatNotificationService;

import org.springframework.beans.factory.annotation.Autowired;
import com.imut.lagain.config.WeChatConfig;
import com.imut.lagain.util.WechatUtil;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * 微信通知记录服务实现类
 */
@Service
public class WechatNotificationServiceImpl extends ServiceImpl<WechatNotificationMapper, WechatNotification> implements IWechatNotificationService {
    private static final Logger log = LoggerFactory.getLogger(WechatNotificationServiceImpl.class);

    @Autowired
    private WechatNotificationRepository wechatNotificationRepository;

    @Resource
    private WeChatConfig weChatConfig;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String ACCESS_TOKEN_URL = "%s%s?grant_type=client_credential&appid=%s&secret=%s";
    private static final String TEMPLATE_MESSAGE_URL = "%s%s?access_token=%s";
    private static final String CUSTOM_MESSAGE_URL = "%s%s?access_token=%s";
    private static final String UPLOAD_TEMP_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/media/upload?access_token=%s&type=%s";
    private static final String UPLOAD_PERMANENT_MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=%s&type=%s";
    private static final String USER_INFO_URL = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=%s&openid=%s&lang=zh_CN";
    private static final String CREATE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=%s";
    private static final String DELETE_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=%s";
    private static final String GET_MENU_URL = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=%s";
    private static final String SET_INDUSTRY_URL = "https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=%s";
    private static final String GET_TEMPLATE_ID_URL = "https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=%s";
    private static final String GET_ALL_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=%s";
    private static final String DELETE_TEMPLATE_URL = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=%s";

    private static final String ACCESS_TOKEN_CACHE_KEY = "wechat:access_token";
    private static final int ACCESS_TOKEN_EXPIRE_TIME = 7000; // 提前200秒过期

    @Override
    public IPage<WechatNotification> findByUserIdAndEventType(Long userId, String eventType, Page<WechatNotification> page) {
        return null;
    }

    @Override
    public IPage<WechatNotification> findBySendStatus(String sendStatus, Page<WechatNotification> page) {
        return null;
    }

    @Override
    public List<WechatNotification> findPendingNotifications(int size) {
        return null;
    }

    @Override
    public boolean updateSendStatus(Long id, String sendStatus, LocalDateTime sendTime) {
        return false;
    }

    @Override
    public List<Object[]> countBySendStatus() {
        return wechatNotificationRepository.countBySendStatus();
    }

    /**
     * 根据用户ID获取待发送的微信通知记录
     * @param userId 用户ID
     * @param size 记录数量
     * @return 微信通知记录列表
     */
    @Override
    public List<WechatNotification> getPendingNotificationsByUserId(Long userId, int size) {
        QueryWrapper<WechatNotification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("send_status", "PENDING")
                   .orderByAsc("create_time")
                   .last("LIMIT " + size);
        return this.list(queryWrapper);
    }

    /**
     * 根据用户ID获取微信通知记录
     * @param userId 用户ID
     * @param page 分页参数
     * @param eventType 事件类型
     * @param sendStatus 发送状态
     * @return 微信通知记录分页列表
     */
    @Override
    public IPage<WechatNotification> getWechatNotificationsByUserId(Long userId, Page<WechatNotification> page, String eventType, String sendStatus) {
        QueryWrapper<WechatNotification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        if (eventType != null && !eventType.trim().isEmpty()) {
            queryWrapper.eq("event_type", eventType);
        }
        
        if (sendStatus != null && !sendStatus.trim().isEmpty()) {
            queryWrapper.eq("send_status", sendStatus);
        }
        
        queryWrapper.orderByDesc("create_time");
        return this.page(page, queryWrapper);
    }

    /**
     * 根据用户ID获取通知统计信息
     * @param userId 用户ID
     * @return 统计信息
     */
    @Override
    public Map<String, Object> getNotificationStatsByUserId(Long userId) {
        Map<String, Object> stats = new HashMap<>();
        
        QueryWrapper<WechatNotification> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        
        // 总数
        long total = this.count(queryWrapper);
        stats.put("total", total);
        
        // 待发送数量
        QueryWrapper<WechatNotification> pendingWrapper = new QueryWrapper<>();
        pendingWrapper.eq("user_id", userId).eq("send_status", "PENDING");
        long pending = this.count(pendingWrapper);
        stats.put("pending", pending);
        
        // 已发送数量
        QueryWrapper<WechatNotification> sentWrapper = new QueryWrapper<>();
        sentWrapper.eq("user_id", userId).eq("send_status", "SENT");
        long sent = this.count(sentWrapper);
        stats.put("sent", sent);
        
        // 发送失败数量
        QueryWrapper<WechatNotification> failedWrapper = new QueryWrapper<>();
        failedWrapper.eq("user_id", userId).eq("send_status", "FAILED");
        long failed = this.count(failedWrapper);
        stats.put("failed", failed);
        
        return stats;
    }

    @Override
    public boolean sendTemplateMessage(Notification notification, NotificationTemplate template, Map<String, Object> data) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                log.error("获取微信Access Token失败");
                return false;
            }

            log.info("构建模板消息数据");
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", notification.getUserId().toString()); // 这里需要用户的OpenID
            messageData.put("template_id", template.getTemplateId());
            messageData.put("url", template.getRedirectUrl());
            messageData.put("topcolor", "#FF0000");
            messageData.put("data", buildTemplateData(template, data));

            log.info("如果有小程序页面，添加小程序信息");
            if (template.getMiniProgramPage() != null && !template.getMiniProgramPage().isEmpty()) {
                Map<String, Object> miniProgram = new HashMap<>();
                miniProgram.put("appid", weChatConfig.getMiniProgramAppId());
                miniProgram.put("pagepath", template.getMiniProgramPage());
                messageData.put("miniprogram", miniProgram);
            }

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送模板消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendTextMessage(String openId, String content) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "text");
            
            Map<String, Object> textData = new HashMap<>();
            textData.put("content", content);
            messageData.put("text", textData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送文本消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendImageMessage(String openId, String mediaId) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "image");
            
            Map<String, Object> imageData = new HashMap<>();
            imageData.put("media_id", mediaId);
            messageData.put("image", imageData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送图片消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendVoiceMessage(String openId, String mediaId) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "voice");
            
            Map<String, Object> voiceData = new HashMap<>();
            voiceData.put("media_id", mediaId);
            messageData.put("voice", voiceData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送语音消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendVideoMessage(String openId, String mediaId, String title, String description) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "video");
            
            Map<String, Object> videoData = new HashMap<>();
            videoData.put("media_id", mediaId);
            videoData.put("title", title);
            videoData.put("description", description);
            messageData.put("video", videoData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送视频消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendMusicMessage(String openId, String title, String description, String musicUrl, String hqMusicUrl, String thumbMediaId) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "music");
            
            Map<String, Object> musicData = new HashMap<>();
            musicData.put("title", title);
            musicData.put("description", description);
            musicData.put("musicurl", musicUrl);
            musicData.put("hqmusicurl", hqMusicUrl);
            musicData.put("thumb_media_id", thumbMediaId);
            messageData.put("music", musicData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送音乐消息失败", e);
            return false;
        }
    }

    @Override
    public boolean sendNewsMessage(String openId, String title, String description, String url, String picUrl) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }

            Map<String, Object> messageData = new HashMap<>();
            messageData.put("touser", openId);
            messageData.put("msgtype", "news");
            
            Map<String, Object> article = new HashMap<>();
            article.put("title", title);
            article.put("description", description);
            article.put("url", url);
            article.put("picurl", picUrl);
            
            Map<String, Object> newsData = new HashMap<>();
            newsData.put("articles", Arrays.asList(article));
            messageData.put("news", newsData);

            return sendCustomMessage(accessToken, messageData);
        } catch (Exception e) {
            log.error("发送图文消息失败", e);
            return false;
        }
    }

    @Override
    public String getAccessToken() {
        try {
            log.info("先从缓存获取");
            String cachedToken = (String) redisTemplate.opsForValue().get(ACCESS_TOKEN_CACHE_KEY);
            if (cachedToken != null && !cachedToken.isEmpty()) {
                return cachedToken;
            }

            log.info("缓存中没有，重新获取");
            return refreshAccessToken();
        } catch (Exception e) {
            log.error("获取Access Token失败", e);
            return null;
        }
    }

    @Override
    public String refreshAccessToken() {
        try {
            String url = String.format(ACCESS_TOKEN_URL, 
                weChatConfig.getApiBaseUrl(), 
                "/cgi-bin/token", 
                weChatConfig.getAppid(), 
                weChatConfig.getSecret());
            
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            Map<String, Object> result = response.getBody();
            
            if (result != null && result.containsKey("access_token")) {
                String accessToken = result.get("access_token").toString();
                Integer expiresIn = Integer.parseInt(result.get("expires_in").toString());
                
                log.info("缓存到Redis，提前200秒过期");
                redisTemplate.opsForValue().set(ACCESS_TOKEN_CACHE_KEY, accessToken, 
                    Math.min(expiresIn - 200, ACCESS_TOKEN_EXPIRE_TIME), TimeUnit.SECONDS);
                
                log.info("微信Access Token刷新成功，有效期: {}秒", expiresIn);
                return accessToken;
            } else {
                log.error("刷新Access Token失败: {}", result);
                return null;
            }
        } catch (Exception e) {
            log.error("刷新Access Token异常", e);
            return null;
        }
    }

    @Override
    public String uploadTempMedia(String type, String filePath) {
        log.info("TODO: 实现临时素材上传");
        return null;
    }

    @Override
    public String uploadPermanentMedia(String type, String filePath, String title, String introduction) {
        log.info("TODO: 实现永久素材上传");
        return null;
    }

    @Override
    public Map<String, Object> getUserInfo(String openId) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return null;
            }
            
            String url = String.format(USER_INFO_URL, accessToken, openId);
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return null;
        }
    }

    @Override
    public boolean createMenu(String menuJson) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }
            
            String url = String.format(CREATE_MENU_URL, accessToken);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<String> entity = new HttpEntity<>(menuJson, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            Map<String, Object> result = response.getBody();
            return result != null && "0".equals(result.get("errcode").toString());
        } catch (Exception e) {
            log.error("创建菜单失败", e);
            return false;
        }
    }

    @Override
    public boolean deleteMenu() {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }
            
            String url = String.format(DELETE_MENU_URL, accessToken);
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            
            Map<String, Object> result = response.getBody();
            return result != null && "0".equals(result.get("errcode").toString());
        } catch (Exception e) {
            log.error("删除菜单失败", e);
            return false;
        }
    }

    @Override
    public Map<String, Object> getMenu() {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return null;
            }
            
            String url = String.format(GET_MENU_URL, accessToken);
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("获取菜单失败", e);
            return null;
        }
    }

    @Override
    public boolean setIndustry(String industryId1, String industryId2) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }
            
            String url = String.format(SET_INDUSTRY_URL, accessToken);
            Map<String, Object> data = new HashMap<>();
            data.put("industry_id1", industryId1);
            data.put("industry_id2", industryId2);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(data, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            Map<String, Object> result = response.getBody();
            return result != null && "0".equals(result.get("errcode").toString());
        } catch (Exception e) {
            log.error("设置行业失败", e);
            return false;
        }
    }

    @Override
    public String getTemplateId(String templateIdShort) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return null;
            }
            
            String url = String.format(GET_TEMPLATE_ID_URL, accessToken);
            Map<String, Object> data = new HashMap<>();
            data.put("template_id_short", templateIdShort);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(data, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            Map<String, Object> result = response.getBody();
            if (result != null && "0".equals(result.get("errcode").toString())) {
                return result.get("template_id").toString();
            }
            return null;
        } catch (Exception e) {
            log.error("获取模板ID失败", e);
            return null;
        }
    }

    @Override
    public Map<String, Object> getAllPrivateTemplate() {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return null;
            }
            
            String url = String.format(GET_ALL_TEMPLATE_URL, accessToken);
            ResponseEntity<Map> response = restTemplate.getForEntity(url, Map.class);
            return response.getBody();
        } catch (Exception e) {
            log.error("获取所有模板失败", e);
            return null;
        }
    }

    @Override
    public boolean deleteTemplate(String templateId) {
        try {
            String accessToken = getAccessToken();
            if (accessToken == null) {
                return false;
            }
            
            String url = String.format(DELETE_TEMPLATE_URL, accessToken);
            Map<String, Object> data = new HashMap<>();
            data.put("template_id", templateId);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(data, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            Map<String, Object> result = response.getBody();
            return result != null && "0".equals(result.get("errcode").toString());
        } catch (Exception e) {
            log.error("删除模板失败", e);
            return false;
        }
    }

    @Override
    public boolean checkSignature(String signature, String timestamp, String nonce, String token) {
        try {
            String[] arr = new String[]{token, timestamp, nonce};
            Arrays.sort(arr);
            
            StringBuilder content = new StringBuilder();
            for (String s : arr) {
                content.append(s);
            }
            
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(content.toString().getBytes(StandardCharsets.UTF_8));
            
            StringBuilder hexStr = new StringBuilder();
            for (byte b : digest) {
                String shaHex = Integer.toHexString(b & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            
            return hexStr.toString().equals(signature);
        } catch (Exception e) {
            log.error("验证签名失败", e);
            return false;
        }
    }

    @Override
    public String handleMessage(String xmlData) {
        try {
            Map<String, String> messageMap = WechatUtil.parseXml(xmlData);
            String msgType = messageMap.get("MsgType");
            String fromUser = messageMap.get("FromUserName");
            String toUser = messageMap.get("ToUserName");
            
            log.info("收到微信消息: msgType={}, fromUser={}", msgType, fromUser);
            
            log.info("根据消息类型处理");
            switch (msgType) {
                case "text":
                    String content = messageMap.get("Content");
                    return handleTextMessage(fromUser, toUser, content);
                case "image":
                case "voice":
                case "video":
                case "shortvideo":
                case "location":
                case "link":
                default:
                    return "success";
            }
        } catch (Exception e) {
            log.error("处理消息失败", e);
            return "success";
        }
    }

    @Override
    public String handleEvent(String xmlData) {
        try {
            Map<String, String> eventMap = WechatUtil.parseXml(xmlData);
            String event = eventMap.get("Event");
            String fromUser = eventMap.get("FromUserName");
            String toUser = eventMap.get("ToUserName");
            
            log.info("收到微信事件: event={}, fromUser={}", event, fromUser);
            
            return handleEventMessage(fromUser, toUser, event, eventMap);
        } catch (Exception e) {
            log.error("处理事件失败", e);
            return "success";
        }
    }

    private boolean sendCustomMessage(String accessToken, Map<String, Object> messageData) {
        try {
            String url = String.format(CUSTOM_MESSAGE_URL, 
                weChatConfig.getApiBaseUrl(), 
                "/cgi-bin/message/custom/send", 
                accessToken);
            
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            
            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(messageData, headers);
            ResponseEntity<Map> response = restTemplate.postForEntity(url, entity, Map.class);
            
            Map<String, Object> result = response.getBody();

            if (result != null && "0".equals(result.get("errcode").toString())) {
                log.info("微信客服消息发送成功");
                return true;
            } else {
                log.error("微信客服消息发送失败: {}", result);
                return false;
            }
        } catch (Exception e) {
            log.error("发送客服消息异常", e);
            return false;
        }
    }

    private Map<String, Object> buildTemplateData(NotificationTemplate template, Map<String, Object> data) {
        Map<String, Object> templateData = new HashMap<>();
        
        try {
            log.info("解析模板的微信数据结构");
            if (template.getWechatData() != null && !template.getWechatData().isEmpty()) {
                Map<String, Object> wechatDataStructure = objectMapper.readValue(template.getWechatData(), Map.class);
                
                for (Map.Entry<String, Object> entry : wechatDataStructure.entrySet()) {
                    String fieldName = entry.getKey();
                    Map<String, Object> valueConfig = (Map<String, Object>) entry.getValue();
                    
                    Map<String, Object> fieldData = new HashMap<>();
                    
                    log.info("获取数据值");
                    String dataKey = (String) valueConfig.get("key");
                    Object value = data.get(dataKey);
                    if (value != null) {
                        fieldData.put("value", value.toString());
                    } else {
                        fieldData.put("value", valueConfig.get("default"));
                    }
                    
                    if (valueConfig.containsKey("color")) {
                        fieldData.put("color", valueConfig.get("color"));
                    }
                    
                    templateData.put(fieldName, fieldData);
                }
            }
        } catch (Exception e) {
            log.error("构建模板数据失败", e);
        }
        
        return templateData;
    }

    private String handleTextMessage(String fromUser, String toUser, String content) {
        try {
            log.info("处理文本消息: fromUser={}, content={}", fromUser, content);
            
            log.info("简单的自动回复逻辑");
            String replyContent = "感谢您的消息，我们已收到！";
            
            log.info("可以根据内容进行不同的回复");
            if (content.contains("帮助") || content.contains("help")) {
                replyContent = "欢迎使用Forever Love！\n\n" +
                        "💕 这里是专属于情侣的温馨空间\n" +
                        "📝 您可以记录美好回忆\n" +
                        "🎁 创建专属的记忆胶囊\n" +
                        "💌 发送温馨的情话\n\n" +
                        "如需更多帮助，请访问我们的官网。";
            } else if (content.contains("功能")) {
                replyContent = "Forever Love 主要功能：\n\n" +
                        "1. 💝 记忆胶囊 - 保存珍贵回忆\n" +
                        "2. 💕 情话生成 - AI生成专属情话\n" +
                        "3. 📅 纪念日提醒 - 重要日子不忘记\n" +
                        "4. 🎵 音乐分享 - 分享你们的专属歌单";
            }
            
            return WechatUtil.buildTextResponse(fromUser, toUser, replyContent);
        } catch (Exception e) {
            log.error("处理文本消息失败", e);
            return "success";
        }
    }

    private String handleEventMessage(String fromUser, String toUser, String event, Map<String, String> eventData) {
        try {
            log.info("处理事件消息: fromUser={}, event={}", fromUser, event);
            
            switch (event) {
                case "subscribe":
                    log.info("关注事件");
                    String welcomeMsg = "🎉 欢迎关注Forever Love！\n\n" +
                            "💕 这里是专属于情侣的温馨空间\n" +
                            "在这里，你们可以：\n" +
                            "📝 记录美好回忆\n" +
                            "🎁 创建记忆胶囊\n" +
                            "💌 生成专属情话\n\n" +
                            "让爱情更加甜蜜，让回忆永远珍藏！";
                    return WechatUtil.buildTextResponse(fromUser, toUser, welcomeMsg);
                    
                case "unsubscribe":
                    log.info("取消关注事件");
                    log.info("用户取消关注: {}", fromUser);
                    return "success";
                    
                case "CLICK":
                    log.info("菜单点击事件");
                    String eventKey = eventData.get("EventKey");
                    return handleMenuClick(fromUser, toUser, eventKey);
                    
                case "VIEW":
                    log.info("菜单跳转事件");
                    String url = eventData.get("EventKey");
                    log.info("用户点击菜单跳转: fromUser={}, url={}", fromUser, url);
                    return "success";
                    
                default:
                    log.info("未处理的事件类型: {}", event);
                    return "success";
            }
        } catch (Exception e) {
            log.error("处理事件消息失败", e);
            return "success";
        }
    }

    private String handleMenuClick(String fromUser, String toUser, String eventKey) {
        try {
            String replyContent;
            switch (eventKey) {
                case "MEMORY_CAPSULE":
                    replyContent = "💝 记忆胶囊功能\n\n" +
                            "在这里，你们可以：\n" +
                            "📸 上传珍贵照片\n" +
                            "📝 写下美好回忆\n" +
                            "⏰ 设置开启时间\n" +
                            "🎁 给未来的自己一个惊喜\n\n" +
                            "点击下方链接开始创建吧！";
                    break;
                case "LOVE_WORDS":
                    replyContent = "💌 AI情话生成\n\n" +
                            "让AI为你们生成专属情话：\n" +
                            "💕 甜蜜情话\n" +
                            "🌹 浪漫诗句\n" +
                            "💝 表白神器\n" +
                            "🎭 趣味对话\n\n" +
                            "让每一句话都充满爱意！";
                    break;
                case "ANNIVERSARY":
                    replyContent = "📅 纪念日提醒\n\n" +
                            "重要的日子不再错过：\n" +
                            "💕 恋爱纪念日\n" +
                            "💒 结婚纪念日\n" +
                            "🎂 生日提醒\n" +
                            "🎉 自定义纪念日\n\n" +
                            "让爱情的每个重要时刻都被铭记！";
                    break;
                case "MUSIC_SHARE":
                    replyContent = "🎵 音乐分享\n\n" +
                            "分享你们的专属音乐：\n" +
                            "💕 情歌推荐\n" +
                            "🎼 专属歌单\n" +
                            "🎤 K歌记录\n" +
                            "🎧 音乐心情\n\n" +
                            "用音乐记录你们的爱情故事！";
                    break;
                case "CONTACT_US":
                    replyContent = "📞 联系我们\n\n" +
                            "如果您有任何问题或建议：\n" +
                            "📧 邮箱：support@foreverlove.com\n" +
                            "📱 客服热线：400-123-4567\n" +
                            "🕐 服务时间：9:00-18:00\n\n" +
                            "我们会尽快为您解答！";
                    break;
                default:
                    replyContent = "感谢您的关注！如需帮助，请发送'帮助'获取更多信息。";
                    break;
            }
            
            return WechatUtil.buildTextResponse(fromUser, toUser, replyContent);
        } catch (Exception e) {
            log.error("处理菜单点击失败", e);
            return "success";
        }
    }
}